package cn.imvc.data.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import cn.imvc.data.domain.ViewRequest;

public class PageableUtil {
	public static Pageable toPageable(ViewRequest viewRequest) {
		if (viewRequest == null)
			viewRequest = new ViewRequest();
		List<Order> orders = new ArrayList<Order>();
		Sort sort = null;
		if (viewRequest.getSort() != null && !viewRequest.getSort().isEmpty()) {
			for (String key : viewRequest.getSort().keySet()) {
				String value = viewRequest.getSort().get(key);
				if (!value.isEmpty()) {
					Order order = new Order(Direction.fromStringOrNull(value
							.trim()), key.trim());
					orders.add(order);
				}
			}
		}
		if (!orders.isEmpty()) {
			sort = new Sort(orders);
		}

		return new PageRequest(viewRequest.getPage(), viewRequest.getSize(),
				sort);
	}
}
